package ui;

import engine.Candidate;
import engine.Constraint;
import engine.GeneticAlgorithm;
import engine.MutateType;
import engine.Population;
import engine.PopulationGenerator;
import engine.Simulation;
import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.concurrent.ExecutionException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import utilities.InvalidFormatException;
import utilities.MatLabCOM;
import utilities.ProblemParser;
import utilities.RandomNumeric;

public class SimulationUI extends javax.swing.JFrame {

    private Simulation simu;
    private JFileChooser fileChooser;

    public SimulationUI() {
        this.setLocationRelativeTo(null);
        initComponents();
        makeRadioButtonGroups();

        this.fileChooser = new JFileChooser(new File(".").getAbsolutePath());

        //Instance Simulation
        this.simu = new Simulation();

        //Instance de MatLabCOM
        this.simu.setMatlab(new MatLabCOM());
    }

    private void makeRadioButtonGroups() {
        buttonGroupMutate.add(rButMutateSub);
        buttonGroupMutate.add(rButMutateSwap);
    }

    //<editor-fold defaultstate="collapsed" desc="Updates UI from Outside">
    /*
     * Màj l'UI pour l'avancement de l'algo, value entre 0 et 100 inclus
     */
    public void updateProgressAlgo(Integer value) {
        progresseBarAlgo.setValue(value);
        lblProgress.setText(value + "%");
    }

    /*
     * Màj l'UI pour l'avancement de la génération de la population, value entre 0 et 100 inclus
     */
    public void updateProgressGenPop(final Integer value) {
        //progressPopGen.setValue(value);
    }

    public void displayErrorPopup(final SimulationUI gui, final String msg) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                JOptionPane.showMessageDialog(gui, msg, "Error", JOptionPane.ERROR_MESSAGE);
            }
        });
        
    }

    /*
     * Màj la durée écoulée par l'algo (en ms)
     */
    public void updateElapsedTime(Integer elapsedMs) {
        long minutes = elapsedMs / 1000 / 60;
        long seconds = elapsedMs / 1000 - minutes * 60;

        DecimalFormat df = new DecimalFormat("00");

        lblTime.setText(df.format(minutes) + " : " + df.format(seconds));
    }

    public void updateSolution(Double bestFitness, Candidate bestCandidate) {
        if (bestFitness == 0.) {
            lblBestFitness.setText("___");
        } else {
            lblBestFitness.setText(new DecimalFormat("0.##E0").format(bestFitness));
        }

        if (bestCandidate == null) {
            lblBestCandidate.setText("___");
        } else {
            lblBestCandidate.setText(bestCandidate.toString());
        }
    }
    //</editor-fold>

    private void fillProblem() {

        String problemFromString = txtAreaProblem.getText();

        //Crée FileParser
        this.simu.setProblemParser(new ProblemParser(problemFromString, txtVarName.getText()));

        //Fill Problem
        try {
            System.out.println("Parsing Problem...");
            this.simu.getAlgo().setProblem(this.simu.getProblemParser().problemFromString());
        } catch (IOException | InvalidFormatException ex) {
            JOptionPane.showMessageDialog(this, ex.toString(), "Error", JOptionPane.ERROR_MESSAGE);
        }
    }

    /*
     * Nécessite que l'objet Problem de la simulation soit fill
     */
    private void fillPopulation() {
        if (this.simu.getAlgo().getProblem() == null) {
            return;
        }

        Integer populationToGenerate = Integer.parseInt(txtPopSize.getText());
        PopulationGenerator generator = new PopulationGenerator(new RandomNumeric(), this.simu.getMatlab(),
                this.simu.getAlgo().getProblem().getConstraint(),
                populationToGenerate, this, Integer.parseInt(txtMaxComputation.getText()));

        Constraint g = this.simu.getAlgo().getProblem().getConstraint();
        Integer popSize = Integer.parseInt(txtPopSize.getText());

        System.out.println("Generating Population...");
        generator.execute();
        Population pop;
        try {
            pop = generator.get();
            this.simu.getAlgo().setPopulation(pop);
        } catch (InterruptedException | ExecutionException ex) {
            Logger.getLogger(SimulationUI.class.getName()).log(Level.SEVERE, null, ex);
        }

        System.out.println(popSize + " candidates generated");
    }

    //<editor-fold defaultstate="collapsed" desc="Events Boutons">
    private void boutonConnect() {
        //Connection asynchrone à MatLab
        this.simu.getMatlab().setLocation(txtMatlabLocation.getText());
        System.out.println("Connexion to MatLab...");
        new Thread(this.simu.getMatlab()).start();
    }

    private void boutonLoadFile() {
        //On passe le fichier séléctionné à un FileParser
        int returnVal = fileChooser.showOpenDialog(this);

        if (returnVal == JFileChooser.APPROVE_OPTION) {
            this.simu.setCurrentFile(fileChooser.getSelectedFile());

            //label fichier courant
            lblCurrentFileName.setText(fileChooser.getSelectedFile().getName());

            String fileToString;
            try {
                fileToString = ProblemParser.readFile(fileChooser.getSelectedFile());

                //Fill textArea
                txtAreaProblem.setText(fileToString);
            } catch (IOException ex) {
                //TO DO Popup
            }
        }
    }

    private void boutonOptimize() {
        //Reset progressBar (car peut etre avoir deja fait une optimisation avant)
        updateProgressAlgo(0);
        updateProgressGenPop(0);
        //Reset solution
        updateSolution(0., null);

        if (!this.simu.getMatlab().getIsConnectedToMatLab()) {
            JOptionPane.showMessageDialog(this, "MatLab conexion unestablished.", "Error", JOptionPane.ERROR_MESSAGE);
            return;
        }
        Double mutateRate = Double.parseDouble(txtMutateRate.getText()) / 100.0f;
        Double mutateIntensity = Double.parseDouble(txtMutateIntensity.getText()) / 100.0f;
        Double selectionRatio = Double.parseDouble(txtSelectRatio.getText()) / 100.0f;

        Long startTime = System.currentTimeMillis();
        Long timeOut = Long.parseLong(txtTimeout.getText()) * 60 * 1000;//min -> ms

        MutateType mutateType = rButMutateSub.isSelected() ? MutateType.MUTATE_SUBSTITUTE : MutateType.MUTATE_SWAP;

        GeneticAlgorithm algo = new GeneticAlgorithm(this.simu.getRandomizer(), this, mutateType, mutateRate, mutateIntensity,
                selectionRatio, timeOut, startTime);
        algo.setMatlab(this.simu.getMatlab());
        this.simu.setAlgo(algo);

        fillProblem();
        fillPopulation();
        
        //Génération pop failed
        if(this.simu.getAlgo().getPopulation() == null) return;
        
        Thread algoThread = new Thread(algo);
        algoThread.start();
    }

    private void boutonStop() {
        this.simu.getAlgo().stopThread();
    }
    //</editor-fold>

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroupCross = new javax.swing.ButtonGroup();
        buttonGroupMutate = new javax.swing.ButtonGroup();
        buttonGroupSelect = new javax.swing.ButtonGroup();
        jTabbedPane2 = new javax.swing.JTabbedPane();
        jPanel3 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        lblCurrentFileName = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        txtVarName = new javax.swing.JTextField();
        jSeparator1 = new javax.swing.JSeparator();
        butLoadFile = new javax.swing.JButton();
        jLabel7 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        txtAreaProblem = new javax.swing.JTextArea();
        jTabbedPane1 = new javax.swing.JTabbedPane();
        jPanel2 = new javax.swing.JPanel();
        jLabel3 = new javax.swing.JLabel();
        txtMatlabLocation = new javax.swing.JTextField();
        butConnect = new javax.swing.JButton();
        jTabbedPane4 = new javax.swing.JTabbedPane();
        jPanel1 = new javax.swing.JPanel();
        rButMutateSub = new javax.swing.JRadioButton();
        rButMutateSwap = new javax.swing.JRadioButton();
        jLabel5 = new javax.swing.JLabel();
        txtPopSize = new javax.swing.JTextField();
        jLabel12 = new javax.swing.JLabel();
        jLabel13 = new javax.swing.JLabel();
        jLabel14 = new javax.swing.JLabel();
        txtMutateRate = new javax.swing.JTextField();
        txtMutateIntensity = new javax.swing.JTextField();
        txtSelectRatio = new javax.swing.JTextField();
        jLabel15 = new javax.swing.JLabel();
        jLabel16 = new javax.swing.JLabel();
        jLabel17 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        txtMaxComputation = new javax.swing.JTextField();
        butOptimize = new javax.swing.JButton();
        jLabel8 = new javax.swing.JLabel();
        lblBestFitness = new javax.swing.JLabel();
        jLabel10 = new javax.swing.JLabel();
        lblBestCandidate = new javax.swing.JLabel();
        jLabel20 = new javax.swing.JLabel();
        lblTime = new javax.swing.JLabel();
        jLabel18 = new javax.swing.JLabel();
        txtTimeout = new javax.swing.JTextField();
        jLabel19 = new javax.swing.JLabel();
        butStop = new javax.swing.JButton();
        progresseBarAlgo = new javax.swing.JProgressBar();
        lblProgress = new javax.swing.JLabel();
        jMenuBar1 = new javax.swing.JMenuBar();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Projet Simulation");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        jPanel3.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jLabel1.setText("Selected File : ");

        lblCurrentFileName.setText("<None>");

        jLabel2.setText("Variable Name : ");

        txtVarName.setText("X");

        butLoadFile.setText("Load File");
        butLoadFile.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                butLoadFileActionPerformed(evt);
            }
        });

        jLabel7.setText("Input problem (must respect specified format) or load from file");

        txtAreaProblem.setColumns(20);
        txtAreaProblem.setRows(5);
        jScrollPane2.setViewportView(txtAreaProblem);

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jSeparator1)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane2)
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addComponent(jLabel7)
                        .addGap(0, 161, Short.MAX_VALUE))
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(txtVarName, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(lblCurrentFileName, javax.swing.GroupLayout.Alignment.TRAILING))
                        .addGap(18, 18, 18)
                        .addComponent(butLoadFile, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(lblCurrentFileName))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(txtVarName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(butLoadFile, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel7)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jTabbedPane2.addTab("Problem", jPanel3);

        jPanel2.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jLabel3.setText("MatLab location :");

        txtMatlabLocation.setText("D:\\Program Files\\MATLAB\\R2011a\\bin\\matlab.exe");

        butConnect.setText("Connect");
        butConnect.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                butConnectActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(butConnect, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(txtMatlabLocation, javax.swing.GroupLayout.DEFAULT_SIZE, 367, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(txtMatlabLocation, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(butConnect, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        jTabbedPane1.addTab("MatLab", jPanel2);

        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        rButMutateSub.setSelected(true);
        rButMutateSub.setText("Mutate Substitute");

        rButMutateSwap.setText("Mutate Swap");

        jLabel5.setText("Population size :");

        txtPopSize.setText("100");

        jLabel12.setText("Mutate Rate :");

        jLabel13.setText("Mutate Intensity :");

        jLabel14.setText("Selection Ratio :");

        txtMutateRate.setText("1");

        txtMutateIntensity.setText("2");

        txtSelectRatio.setText("90");

        jLabel15.setText("%");

        jLabel16.setText("%");

        jLabel17.setText("%");

        jLabel4.setText("Max Computations :");

        txtMaxComputation.setText("10000");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(rButMutateSub, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(rButMutateSwap, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addGap(37, 37, 37)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel13)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(txtMutateIntensity, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel16))
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel14)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(txtSelectRatio, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel17))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel12)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(txtMutateRate, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel15))))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel5)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtPopSize, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(61, 61, 61)
                        .addComponent(jLabel4)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(txtMaxComputation, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(85, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(30, 30, 30)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(txtPopSize, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4)
                    .addComponent(txtMaxComputation, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(rButMutateSub, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(rButMutateSwap))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel12)
                            .addComponent(txtMutateRate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel15))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel13)
                            .addComponent(txtMutateIntensity, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel16))))
                .addGap(28, 28, 28)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtSelectRatio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel17)
                    .addComponent(jLabel14))
                .addGap(58, 58, 58))
        );

        jTabbedPane4.addTab("Genetic Algorithm Parameters", jPanel1);

        butOptimize.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        butOptimize.setText("Optimize");
        butOptimize.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                butOptimizeActionPerformed(evt);
            }
        });

        jLabel8.setText("Best Fitness :");

        lblBestFitness.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        lblBestFitness.setText("___");

        jLabel10.setText("Best Candidate :");

        lblBestCandidate.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        lblBestCandidate.setText("___");

        jLabel20.setText("Time :");

        lblTime.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        lblTime.setText("00 : 00");
        lblTime.setToolTipText("");

        jLabel18.setText("Timeout :");

        txtTimeout.setText("5");

        jLabel19.setText("min");

        butStop.setText("Stop");
        butStop.setPreferredSize(new java.awt.Dimension(55, 25));
        butStop.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                butStopActionPerformed(evt);
            }
        });

        lblProgress.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        lblProgress.setText("0%");

        jMenuBar1.setDoubleBuffered(true);
        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jTabbedPane2)
                            .addComponent(jTabbedPane1, javax.swing.GroupLayout.Alignment.TRAILING))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jTabbedPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(jLabel20)
                                        .addGap(18, 18, 18)
                                        .addComponent(lblTime, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(jLabel18)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(txtTimeout, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(jLabel19)))
                                .addGap(18, 18, 18)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel10)
                                    .addComponent(jLabel8))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(lblBestFitness)
                                    .addComponent(lblBestCandidate))
                                .addGap(0, 0, Short.MAX_VALUE))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(progresseBarAlgo, javax.swing.GroupLayout.PREFERRED_SIZE, 274, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(47, 47, 47)
                                .addComponent(lblProgress, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(butOptimize, javax.swing.GroupLayout.PREFERRED_SIZE, 797, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(butStop, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(10, 10, 10)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jTabbedPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 248, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jTabbedPane4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jLabel10)
                                .addComponent(lblBestCandidate))
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(jLabel20)
                                    .addComponent(lblTime))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(jLabel18)
                                    .addComponent(txtTimeout, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jLabel19)
                                    .addComponent(jLabel8)
                                    .addComponent(lblBestFitness))))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lblProgress, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(progresseBarAlgo, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(butOptimize, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(butStop, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(13, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void butConnectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_butConnectActionPerformed
        boutonConnect();
    }//GEN-LAST:event_butConnectActionPerformed

    //Fermeture de la fenetre
    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        //Déconnection de matlab
        MatLabCOM matlab = this.simu.getMatlab();
        if (matlab != null) {
            matlab.disconnect();
        }
    }//GEN-LAST:event_formWindowClosing

    private void butLoadFileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_butLoadFileActionPerformed
        boutonLoadFile();
    }//GEN-LAST:event_butLoadFileActionPerformed

    private void butOptimizeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_butOptimizeActionPerformed
        boutonOptimize();
    }//GEN-LAST:event_butOptimizeActionPerformed

    private void butStopActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_butStopActionPerformed
        boutonStop();
    }//GEN-LAST:event_butStopActionPerformed

    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(SimulationUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(SimulationUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(SimulationUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(SimulationUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new SimulationUI().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton butConnect;
    private javax.swing.JButton butLoadFile;
    private javax.swing.JButton butOptimize;
    private javax.swing.JButton butStop;
    private javax.swing.ButtonGroup buttonGroupCross;
    private javax.swing.ButtonGroup buttonGroupMutate;
    private javax.swing.ButtonGroup buttonGroupSelect;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel13;
    private javax.swing.JLabel jLabel14;
    private javax.swing.JLabel jLabel15;
    private javax.swing.JLabel jLabel16;
    private javax.swing.JLabel jLabel17;
    private javax.swing.JLabel jLabel18;
    private javax.swing.JLabel jLabel19;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel20;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JTabbedPane jTabbedPane2;
    private javax.swing.JTabbedPane jTabbedPane4;
    private javax.swing.JLabel lblBestCandidate;
    private javax.swing.JLabel lblBestFitness;
    private javax.swing.JLabel lblCurrentFileName;
    private javax.swing.JLabel lblProgress;
    private javax.swing.JLabel lblTime;
    private javax.swing.JProgressBar progresseBarAlgo;
    private javax.swing.JRadioButton rButMutateSub;
    private javax.swing.JRadioButton rButMutateSwap;
    private javax.swing.JTextArea txtAreaProblem;
    private javax.swing.JTextField txtMatlabLocation;
    private javax.swing.JTextField txtMaxComputation;
    private javax.swing.JTextField txtMutateIntensity;
    private javax.swing.JTextField txtMutateRate;
    private javax.swing.JTextField txtPopSize;
    private javax.swing.JTextField txtSelectRatio;
    private javax.swing.JTextField txtTimeout;
    private javax.swing.JTextField txtVarName;
    // End of variables declaration//GEN-END:variables
}
